const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  USER_IS_EXIST,
  SERVER_ERR,
  USER_IS_NOT_EXIST,
  PASSWORD_IS_NOT_RIGHT,
} = require("../config/error");
const userService = require("../service/user.service");
const { setToken } = require("../utils/disposeToken");

const verifyLogin = async (ctx, next) => {
  try {
    const { name, password } = ctx.request.body;
    const res = await userService.findName(name);

    // 边界判断
    if (!res.length) {
      ctx.app.emit("error", USER_IS_NOT_EXIST, ctx);
      return;
    }
    if (password !== res[0].password) {
      ctx.app.emit("error", PASSWORD_IS_NOT_RIGHT, ctx);
      return;
    }
    // 设置token
    ctx.author = {
      token: setToken({
        id: res[0].id,
        name: res[0].name,
      }),
    };

    await next();
  } catch (error) {
    ctx.error = error;
    ctx.app.emit("error", SERVER_ERR, ctx);
  }
};
module.exports = verifyLogin;
